import React, {useEffect, useState} from 'react'
import {Button, Input, Layout, message, Space, Typography, Upload} from "antd";
import {UploadOutlined, InfoCircleOutlined, QuestionCircleOutlined, SendOutlined} from '@ant-design/icons'
import './Hole.css'
function getBase64(file) {
  return new Promise((resolve, reject)=>{
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      resolve(reader.result);
    };
    reader.onerror = function (error) {
      reject('Error: ', error);
    };
  })
}

const { Header, Content, Footer } = Layout;

function setCookie(cname, cvalue, exdays) {
  localStorage.setItem(cname, cvalue)
  // const d = new Date();
  // d.setTime(d.getTime() + (exdays*24*60*60*1000));
  // let expires = "expires="+ d.toUTCString();
  // document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  return localStorage.getItem(cname)
  // let name = cname + "=";
  // let decodedCookie = decodeURIComponent(document.cookie);
  // let ca = decodedCookie.split(';');
  // for(let i = 0; i <ca.length; i++) {
  //   let c = ca[i];
  //   while (c.charAt(0) === ' ') {
  //     c = c.substring(1);
  //   }
  //   if (c.indexOf(name) === 0) {
  //     return c.substring(name.length, c.length);
  //   }
  // }
  // return "";
}

function Hole () {
  const [fileList, setFileList]=useState([])
  const [content, setContent]=useState('')
  const [token, setToken]=useState('')
  const [loading, setLoading]=useState(false)
  useEffect(()=>{
    let t=getCookie('token')
    if (t){
      setToken(t)
    }
  },[])
  return(
  <Layout className={'layout'}>
    <Header className={'header'}>
      Hole-GIF
    </Header>
    <Content className={'wrapper'}>
      <Typography.Paragraph>
        <Typography.Text type={'secondary'}>
          <QuestionCircleOutlined /> User Token 在树洞网页版信息栏点击“复制 User Token”即可获得。
        </Typography.Text>
      </Typography.Paragraph>
      <Typography.Paragraph>
        <Typography.Text type={'secondary'}>
          <InfoCircleOutlined/> User Token 仅在本地缓存，并将被直接发送到树洞服务器，不会泄露。
        </Typography.Text>
      </Typography.Paragraph>
      <Space style={{width: '100%'}} direction={'vertical'}>
        <Input value={content} onChange={(e)=>setContent(e.target.value)} placeholder={'内容'}/>
        <Input value={token} onChange={(e)=> {
          setToken(e.target.value)
          setCookie('token', e.target.value, 365)
        }} placeholder={'User Token'}/>
        <Upload
          listType="picture"
          customRequest={(obj)=>{
            if (obj.file.size>1024*1024*2){
              message.error('文件太大，请选择小于 2MB 的图片')
              obj.onError()
              return
            }
            getBase64(obj.file).then((base64)=>{
              console.log(base64)
              obj.file.base64=base64.slice(base64.indexOf(',')+1)
              obj.onSuccess()
            }).catch(()=>{
              message.error('文件转换失败')
            })
          }}
          onChange={info => {
            setFileList([...info.fileList].slice(-1));
          }}
          fileList={fileList}
          accept={"image/*"}
        >
          <Button icon={<UploadOutlined />}>上传</Button>
        </Upload>
        <Button icon={<SendOutlined />} block type={'primary'} loading={loading} onClick={()=>{
          const base64=fileList[0]?.base64
          if (!token) {
            message.error('请输入 User Token')
            return
          }
          if (!content && !base64) {
            message.error('请输入文字内容或上传图片')
            return
          }
          setLoading(true)
          let urlencoded = new URLSearchParams();
          urlencoded.append("text", content);
          urlencoded.append("type", base64?"image":"text");
          urlencoded.append("user_token", token);
          base64 && urlencoded.append("data", base64);
          let requestOptions = {
            method: 'POST',
            body: urlencoded,
            redirect: 'follow'
          };
          fetch("https://pkuhelper.pku.edu.cn/services/pkuhole/api.php?action=dopost&PKUHelperAPI=3.0&jsapiver=201027113050-455946&user_token="+token, requestOptions)
            .then(response => response.json())
            .then(result => {
              console.log(result)
              if (result.code){
                if (result.msg==='请更新PKU Helper客户端至最新版本并登录 (pkuhelper.pku.edu.cn). 谢谢!'){
                  message.error('发送错误：可能由于 token 不正确')
                }else{
                  message.error('发送错误：'+result.msg)
                }
              }else{
                message.success(<>发送成功，树洞编号为 <Typography.Text copyable>{result.data}</Typography.Text></>)
              }
              setLoading(false)
            })
            .catch(error => {
              message.error('网络错误')
              console.log('error', error)
              setLoading(false)
            });
        }}>提交</Button>
      </Space>
    </Content>
    <Footer style={{ textAlign: 'center' }}>Eddie 💕</Footer>

  </Layout>)
}

export default Hole
